<?php

namespace app\model;

use app\common\controller\PreciseCalculator;
use think\Model;

class OutsourcingOrderModel extends BaseModel
{
    protected $name = 'outsourcing_order';

    public const STATUS_PENDING_PRODUCTION = 100;  //待生产
    public const STATUS_IN_PRODUCTION = 200; //生产中
    public const STATUS_PRODUCTION_COMPLETED = 300; //生产完成
    public const STATUS_DELIVERED = 400; //交付入库


    /**
     * Notes: 增加外协订单
     * User: chenLei
     * Date: 11/14/25 12:49:02
     * @param $params
     * @return false|void
     */
    public function add($params)
    {
        $order = OrderModel::where('id', $params['dingdan_id'])->findOrEmpty();
        if ($order->isEmpty()) {
            $this->error = '订单不存在';
            return false;
        }

        $data = [];
        foreach ($params['material'] as $value) {

            $material = MaterialCategoryModel::where('id', $value['material_id'])->findOrEmpty();
            if ($material->isEmpty()) {
                $this->error = '有物料不存在企业系统仓库';
                return false;
            }

            $sum_cost_price = PreciseCalculator::mul($material['cost_price'], $value['material_quantity']);
            $data[] = [
                'company_id' => $params['company_id'],
                'user_id' => $params['login_user_id'],
                'dingdan_id' => $params['dingdan_id'],
                'material_id' => $value['material_id'],
                'material_name' => $material['material_name'],
                'difference' => $material['spec'] ?? '',
                'material_quantity' => $value['material_quantity'],
                'cost_price' => $material['cost_price'],
                'sum_cost_price' => $sum_cost_price,
                'remark' => $value['remark'] ?? '',
                'status' => self::STATUS_PENDING_PRODUCTION,
            ];
        }

        $this->saveAll($data);

        return true;
    }


    /**
     * Notes: 外协订单列表
     * User: chenLei
     * Date: 11/14/25 13:10:38
     * @param $params
     * @return \think\Paginator
     * @throws \think\db\exception\DbException
     */
    public function outsourcingOrderList($params)
    {

        $where = [];
        if (!empty($params['status'])) {
            $where[] = ['o.status', '=', $params['status']];
        }
        $where[] = ['o.vendors_id', '=', $params['user_id']];
        $list = $this->alias('o')
            ->leftJoin('company c', 'c.id = o.company_id')
            ->leftJoin('dingdan d', 'd.id = o.dingdan_id')
            ->field('o.*,c.name as company_name,d.dingdan_code')
            ->order('o.id desc')
            ->where($where)->paginate($params['page_size'] ?? 15)->each(function ($item) {

            });

        return $list;
    }


    /**
     * Notes: 外协订单详情
     * User: chenLei
     * Date: 11/14/25 13:20:42
     * @param $params
     * @return false
     */
    public function outsourcingOrderInfo($params)
    {
        $info = $this->alias('o')
            ->leftJoin('company c', 'c.id = o.company_id')
            ->leftJoin('dingdan d', 'd.id = o.dingdan_id')
            ->field('o.*,c.name as company_name,d.dingdan_code')
            ->where('o.id', $params['id'])
            ->findOrEmpty();
        if ($info->isEmpty()) {
            $this->error = '订单不存在';
            return false;
        }

        $info = $info->toArray();
        return $info;
    }


    /**
     * Notes: 外协确认开始生产
     * User: chenLei
     * Date: 11/3/25 14:23:15
     * @param $params
     * @return bool
     */
    public function submitProductionExecution($params)
    {

        $info = $this->where('id', $params['id'])->findOrEmpty();
        if ($info->isEmpty()) {
            $this->error = '订单信息已经不存在';
            return false;
        }
        if ($info->status != self::STATUS_PENDING_PRODUCTION) {
            $this->error = '订单状态不等于待生产，请勿操作';
            return false;
        }
        $info->status = self::STATUS_IN_PRODUCTION;
        $info->start_production_time = date('Y-m-d H:i:s');
        $info->save();

        return true;
    }

    /**
     * Notes: 确认交付时间
     * User: chenLei
     * Date: 11/14/25 13:25:46
     * @param $params
     * @return bool
     */
    public function productionCompleted($params)
    {
        $info = $this->where('id', $params['id'])->findOrEmpty();
        if ($info->isEmpty()) {
            $this->error = '订单信息已经不存在';
            return false;
        }
        if ($info->status != self::STATUS_IN_PRODUCTION) {
            $this->error = '订单状态不等于生产中，请勿操作';
            return false;
        }
        $info->status = self::STATUS_PRODUCTION_COMPLETED;
        $info->outsourcing_completed_time = date('Y-m-d H:i:s');
        $info->save();

        return true;
    }


    /**
     * Notes: 外协确认交付
     * User: chenLei
     * Date: 11/3/25 14:27:44
     * @param $params
     * @return bool
     */
    public function wxConfirmDelivery($params)
    {
        $info = $this->where('id', $params['id'])->findOrEmpty();
        if ($info->isEmpty()) {
            $this->error = '订单信息已经不存在';
            return false;
        }
        if ($info->status != self::STATUS_PRODUCTION_COMPLETED) {
            $this->error = '订单状态不等于生产完成，请勿操作';
            return false;
        }
        $info->status = self::STATUS_DELIVERED;
        $info->delivery_time = date('Y-m-d H:i:s');
        $info->save();

        return true;
    }


    /**
     * Notes: 列表
     * User: chenLei
     * Date: 11/15/25 23:43:14
     * @param $params
     * @return mixed
     */
    public function list($params)
    {
        $where = [];
        if (!empty($params['status'])) {
            $where[] = ['o.status', '=', $params['status']];
        }
        if (!empty($params['is_assign'])) {
            if ($params['is_assign'] == 100) {
                $where[] = ['o.vendors_id', '=', 0];
            } else if ($params['is_assign'] == 200) {
                $where[] = ['o.vendors_id', '>', 0];
            }

        }
        $list = $this->alias('o')
            ->leftJoin('company c', 'c.id = o.company_id')
            ->leftJoin('dingdan d', 'd.id = o.dingdan_id')
            ->leftJoin('vendors v', 'v.id = o.vendors_id')
            ->field('o.*,c.name as company_name,d.dingdan_code')
            ->order('o.id desc')
            ->where($where)->paginate($params['page_size'] ?? 15)->each(function ($item) {

            });

        return $list;
    }


    /**
     * Notes: 分配订单
     * User: chenLei
     * Date: 11/15/25 23:54:53
     * @param $params
     * @return bool
     */
    public function assignOrder($params)
    {
        foreach ($params['ids'] as $key => $id) {
            if (!$this->where('id', $id)->where('vendors_id', 0)->count()) {
                unset($params['ids'][$key]);
            }
        }

        if (empty($params['ids'])) {
            $this->error = '没有可分配的订单';
            return false;
        }

        $this->whereIn('id', $params['ids'])->update([
            'vendors_id' => $params['vendors_id'],
            'status' => self::STATUS_PENDING_PRODUCTION,
        ]);

        return true;
    }
}